﻿using System;
using NHibernate;
using NHibernate.Context;

namespace Tanmia.Basis.Data.NHibernate
{
    public class TransactionSpace : IDisposable
    {
        public ISession Session { get; private set; }
        private bool isCommitted;

        public TransactionSpace(ISessionGate sessionGate)
        {
            Session = sessionGate.Session;
            Session.BeginTransaction();
            CurrentSessionContext.Bind(Session);
            isCommitted = false;
        }

        public void Commit()
        {
            Session.Transaction.Commit();
            isCommitted = true;
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (!isCommitted)
                Session.Transaction.Rollback();

            Session.Dispose();
        }

        #endregion
    }
}
